import React, { useState, forwardRef, useImperativeHandle,memo } from 'react'
import { Modal, Select } from 'antd';
import {useSelector,useDispatch} from 'react-redux'
import rolesAction from '../../../redux/action/rolesAction';
import { setRoles } from '../../../api/user';
function SetRoles(props: any, ref: any) {
    let [record, setRecord] = useState<DataTable>()
    let [isModalOpen, setisModalOpen] = useState(false);
    let dispatch = useDispatch<any>();
    let [rollesId,setId] = useState<number>();
    // 获取 仓库中存储的角色列表
    let rolesList:RolesItem[]= useSelector((state:StoreStateType)=>{
        return state.rolesReducer.rolesList
    })
    if(rolesList.length===0){
        dispatch(rolesAction())
    }
    let handleOk = async () => {
        // 发送请求设置角色
        let res = await setRoles(record?.id as number,rollesId as number);
        console.log(res)
        setisModalOpen(false);
        props.over();
    }
    let handleCancel = () => {
        setisModalOpen(false)
    }
    let init = (record: DataTable) => {
        setisModalOpen(true)
        setRecord(record)
    }
    useImperativeHandle(ref, () => {
        return {
            init
        }
    })
    return (
        <Modal title={'分配角色'} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} okText={'确认'} cancelText={'取消'}>
            <div>当前用户：{record?.username}</div>
            <div style={{ margin: "10px 0" }}>当前角色：{record?.role_name}</div>
            <div>
                分配新角色:  <Select
                    style={{ width: 200 }}
                    placeholder='请选择角色'
                    options={rolesList}
                    value={rollesId}
                    onChange={(value)=>{
                        setId(value)
                    }}
                    fieldNames={{
                        value:'id',
                        label:"roleName"
                    }}
                />
            </div>
        </Modal>
    )
}

export default memo(forwardRef(SetRoles))
